package com.xiaoheng999.miya.spingmvc.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.xiaoheng999.miya.spingmvc.model.FileModel;

@Controller
public class FileUploadController {
	//@Autowired
	//ServletContext context;

	@RequestMapping(value = "/fileUploadPage", method = RequestMethod.GET)
	public ModelAndView fileUploadPage() {
		FileModel file = new FileModel();
		ModelAndView modelAndView = new ModelAndView("pages/springmvc/fileupload/fileUpload", "command", file);
		return modelAndView;
	}

	@RequestMapping(value = "/fileUploadPage", method = RequestMethod.POST)
	public String fileUpload(@Validated FileModel file, BindingResult result, ModelMap model) throws IOException {
		if (result.hasErrors()) {
			System.out.println("validation errors");
			return "fileUploadPage";
		} else {
			System.out.println("Fetching file");
			MultipartFile multipartFile = file.getFile();
			String uploadPath = null;//context.getRealPath("") + File.separator + "temp" + File.separator;
			if(!new File(uploadPath).isDirectory()){
				new File(uploadPath).mkdir();
			}
			System.out.println("uploadPath:"+uploadPath);
			// Now do something with file...
			FileCopyUtils.copy(file.getFile().getBytes(), new File(uploadPath + file.getFile().getOriginalFilename()));
			String fileName = multipartFile.getOriginalFilename();
			model.addAttribute("fileName", fileName);
			return "pages/springmvc/fileupload/success";
		}
	}
	
	
	// Upload One File.
    @RequestMapping(value = "/uploadOneFile")
    public String uploadOneFileHandler() {
        return "pages/springmvc/fileupload/uploadOneFile";
    }
 
    // Upload Multi File.
    @RequestMapping(value = "/uploadMultiFile")
    public String uploadMultiFileHandler() {
        // Forward to "/WEB-INF/pages/uploadMultiFile.jsp".
        return "pages/springmvc/fileupload/uploadMultiFile";
    }
    
    
    // uploadOneFile.jsp, uploadMultiFile.jsp submit to.
    @RequestMapping(value = "/doUpload", method = RequestMethod.POST)
    public String uploadFileHandler(HttpServletRequest request, Model model,
            @RequestParam("file") MultipartFile[] files) {
 
        // Root Directory.
        String uploadRootPath = request.getServletContext().getRealPath(
                "upload");
        System.out.println("uploadRootPath=" + uploadRootPath);
 
        File uploadRootDir = new File(uploadRootPath);
        //
        // Create directory if it not exists.
        if (!uploadRootDir.exists()) {
            uploadRootDir.mkdirs();
        }
        //
        List<File> uploadedFiles = new ArrayList<File>();
        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];
 
            // Client File Name
            String name = file.getOriginalFilename();
            System.out.println("Client File Name = " + name);
 
            if (name != null && name.length() > 0) {
                try {
                    byte[] bytes = file.getBytes();
 
                    // Create the file on server
                    File serverFile = new File(uploadRootDir.getAbsolutePath()
                            + File.separator + name);
 
                    // Stream to write data to file in server.
                    BufferedOutputStream stream = new BufferedOutputStream(
                            new FileOutputStream(serverFile));
                    stream.write(bytes);
                    stream.close();
                    //
                    uploadedFiles.add(serverFile);
                    System.out.println("Write file: " + serverFile);
                } catch (Exception e) {
                    System.out.println("Error Write file: " + name);
                }
            }
        }
        model.addAttribute("uploadedFiles", uploadedFiles);
        return "pages/springmvc/fileupload/uploadResult";
    }
}
